package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.CustomerTransfer;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.ICustomerService;
import cn.wolfcode.crm.service.ICustomerTransferService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.UserContext;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/customerTransfer")
public class CustomerTransferController {

    @Autowired
    private ICustomerTransferService customerTransferService;
    @Autowired
    private ICustomerService customerService;

    // 提供一个方法处理查询所有部门数据请求，响应 HTML
    @RequestMapping("/list")
    @RequiresPermissions(value = {"customerTransfer:list", "部门列表"}, logical = Logical.OR)
    public String list(Model model, QueryObject queryObject) {
        PageInfo customerTransferList = customerTransferService.list(queryObject);
        model.addAttribute("result", customerTransferList);
        return "customerTransfer/list"; // /WEB-INF/views/customerTransfer/list.jsp
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    @RequiresPermissions(value = {"customerTransfer:saveOrUpdate", "部门保存/更新"}, logical = Logical.OR)
    public JsonResult saveOrUpdate(CustomerTransfer customerTransfer) {
        if (customerTransfer.getId() == null) { // 代表新增
            customerTransferService.save(customerTransfer);
        } else { // 代表修改
            customerTransferService.update(customerTransfer);
        }
        return new JsonResult();
    }

    @RequestMapping("/absorb")
    @ResponseBody
    public JsonResult absorb(CustomerTransfer customerTransfer) {
        Long id = customerTransfer.getCustomer().getId();
        customerService.updateStatus(id, 0);
        //设置销售为登录人
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        customerTransfer.setNewseller(employee);
        customerTransferService.save(customerTransfer);
        return new JsonResult();
    }

    @RequestMapping("/delete")
    @ResponseBody
    @RequiresPermissions(value = {"customerTransfer:delete", "部门删除"}, logical = Logical.OR)
    public JsonResult delete(Long id) {
        customerTransferService.delete(id);
        return new JsonResult();
    }
}
